package cn.wit.db.security;

import cn.wit.db.entity.Employees;
import cn.wit.db.entity.Role;
import cn.wit.db.mapper.EmployeesMapper;
import cn.wit.db.mapper.RoleMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Set;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
	private static final Logger logger = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

	@Autowired
	private EmployeesMapper mapper;
	
	// 告诉spring security，如何查找用户信息
	
	/// UserDetails: 封装了用户的信息，主要是用户名、密码、权限
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		logger.debug("employee:{}", username);
		
		// 把用户信息和角色信息都查出来
		Employees user = (Employees) mapper.findByName(username);
		if (user == null) {
			throw new UsernameNotFoundException("用户不存在！");
		}
		
		Set<Role> roles = user.getRoles();
		if (roles == null || roles.size() == 0) {
			throw new IllegalStateException("用户未分配任何角色！");
		}
		
		// https://stackoverflow.com/questions/23079003/how-to-convert-a-java-8-stream-to-an-array
		String[] authorities = user.getRoles().stream()
				.map(role -> "ROLE_" + role.getKeyword())		// spring-security权限需要加上ROLE_前缀
				.toArray(String[]::new);

		return User.builder()
			.username(username)
			.password(user.getPassword())
			.authorities(authorities)
			.build();
	}
}
